package com.lhy.mymall.flter;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.lhy.mymall.common.Constant;
import com.lhy.mymall.exception.ExceptionEnum;
import com.lhy.mymall.exception.MallException;
import com.lhy.mymall.pojo.User;
import com.lhy.mymall.service.UserService;
import lombok.SneakyThrows;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author: 卢辉宇
 * @date: 2022/12/14 21:48
 * @description: 用户过滤器，用于判断是否是用户登录的
 */
public class UserJWTFilter implements Filter {


    //定义一个静态的user对象，用于保存当前用户的信息
    public static User currentUser;

    @Resource
    UserService userService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @SneakyThrows
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //解决响应中文乱码问题
        servletResponse.setContentType("json/application;charset=UTF-8");

        //通过servletRequest的子接口的头，拿到token,并设置其key为jwt_token
        HttpServletRequest request =(HttpServletRequest) servletRequest;
        String token = request.getHeader(Constant.JWT_TOKEN);

        //通过传来的token信息判断是否登录
        //判断是否登录
        if (token==null){
            //通过HttpServletResponseWrapper的对象返回json数据给前端
            PrintWriter out = new HttpServletResponseWrapper((HttpServletResponse) servletResponse).getWriter();
            //向前端返回的json数据
            out.write("{\"status\":1007,\"msg\":\"用户未登录!\",\"data\":null}");
            //刷新并关闭
            out.flush();
            out.close();
            //不放行，提前结束
            return;
        }

        /*判断token的真实性*/
        //1.拿到签名密钥
        Algorithm algorithm = Algorithm.HMAC256(Constant.JWT_KEY);
        //2.用jwt的方法拿到验证构造器
        JWTVerifier verifier = JWT.require(algorithm).build();
        try {
            //用验证构造器得到解码的jwt
            DecodedJWT jwt = verifier.verify(token);
            //把jwt转换成user对象,放到当前用户
            currentUser = new User();
            currentUser.setId(jwt.getClaim(Constant.USER_ID).asInt());
            currentUser.setUsername(jwt.getClaim(Constant.USER_NAME).asString());
            currentUser.setRole(jwt.getClaim(Constant.USER_ROLE).asInt());
        }catch (TokenExpiredException e){
            //token已经过期
            throw new MallException(ExceptionEnum.TOKEN_EXPIRED);
        }catch (JWTDecodeException e){
            //token解析失败
            throw new MallException(ExceptionEnum.TOKEN_WRONG);
        }

        //放行
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
